﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;

namespace QuickApp.Core
{
    /// <summary>
    /// UnitOfWork模式
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        // 数据库上下文对象
        private readonly DbContext Context;
        public UnitOfWork(DbContext context)
        {
            this.Context = context;
        }

        /// <summary>
        /// 保存所有的实体数据的更新
        /// </summary>
        public void Commit()
        {
            try
            {
                this.Context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName,
                                      validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
        }
    }
}
